/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/
#pragma once

class kEngine;
class kStream;

#include "kbase.h"
#include "kcommon.h"

class kIniFile : public kBase {
private:
	kEngine* _engine;
	std::map<std::tstring, std::map<std::tstring, std::tstring>> _data;

public:
	kIniFile(kEngine* engine);
	~kIniFile();

	void save(kStream* stream);
	void load(kStream* stream);
	void save(const std::tstring& resourceUri);
	void load(const std::tstring& resourceUri);
	inline void clear() {
		_data.clear();
	}
	inline bool empty() {
		return _data.empty();
	}
	inline void set(const std::tstring& group, const std::tstring& key, const std::tstring& value) {
		_data[group][key] = value;
	}
	template<typename T> inline void set(const std::tstring& group, const std::tstring& key, T value) {
		std::tostringstream stream;
		stream << value;
		_data[group][key] = stream.str();
	}
	inline void unset(const std::tstring& group, const std::tstring& key) {
		std::map<std::tstring, std::tstring>& keys = _data[group];
		keys.erase(key);
		if (keys.empty())
			_data.erase(group);
	}
	inline const std::tstring& get(const std::tstring& group, const std::tstring& key, const std::tstring& def = _T("")) {
		auto i = _data.find(group);
		if (i == _data.end())
			return def;

		auto j = i->second.find(key);
		if (j == i->second.end())
			return def;

		return j->second;
	}
	template<typename T> inline T get(const std::tstring& group, const std::tstring& key, T def) {
		auto i = _data.find(group);
		if (i == _data.end())
			return def;

		auto j = i->second.find(key);
		if (j == i->second.end())
			return def;

		std::tistringstream stream(j->second);
		T t;
		stream >> t;
		return t;
	}
	inline bool exists(const std::tstring& group, const std::tstring& key) {
		auto i = _data.find(group);
		if (i == _data.end())
			return false;

		auto j = i->second.find(key);
		if (j == i->second.end())
			return false;

		return true;
	}

	inline kEngine* getEngine() {
		return _engine;
	}
};
